import Konva from 'konva'
import { Layer } from 'konva/lib/Layer'
import { Shape, ShapeConfig } from 'konva/lib/Shape'
import { Stage } from 'konva/lib/Stage'
import { EGraph, ERecorderBrashColor, ERecorderOperation, ERecorderStatus } from './index'
import svgUrl from '@/assets/images/home/close.svg'
import { Group } from 'konva/lib/Group'
import { EDrawingToolName, EDotDrawingToolName, wPxRatio, hPxRatio } from './boardProperty'
import { createImageText } from './createText'
import { initBoard } from './iniBoard'
import { brush, circleBrush, clearBush, lineBrush, rectangleBrush, triangleBrush } from './brush'
import { browser } from '@/utils/http'
export interface IImageToolManage {
  // /**输出绘图 */
  // canvas: HTMLCanvasElement;
  /** dom标签 */
  dom: HTMLDivElement
  // /**所有layers 对象 */
  // layers: Array<Konva.Shape | Konva.Layer>;
  /**konva */
  stage: Konva.Stage
  color: string
  /**当前激活的对象 */
  activeShape: Konva.Shape | null
  /**当前工具操作*/
  operat: ERecorderOperation
  reflashRequestAnimationFrame: number
  /**颜色 */
  // color: ERecorderBrashColor;
  /** 回退 */
  backspacing: () => void
  /** 画笔 涂鸦 */
  brush: () => void
  /** 贴图 */
  setImage: (url: string, name: string) => void
  /** 文字 */
  setText: () => void
  /** 画图形 */
  drawGraph: (type: EGraph) => void
  /**画板清空 */
  clearAll: () => void
  /** 回归按钮状态*/
  flyback: () => void
}

export class ImageManage implements IImageToolManage {
  dom
  /**输出绘图 */
  // canvas: HTMLCanvasElement;
  /**图像编辑容器 */
  private layers = [] as Array<Konva.Shape>
  bgLayer: Konva.Layer = new Konva.Layer()
  stage
  color = ERecorderBrashColor.black
  /**state数据 */
  state
  zoom
  /**当前按钮互斥位置 */
  operat = ERecorderOperation.none
  /**当前激活的对象 */
  activeShape: Shape<ShapeConfig> | null = null
  reflashRequestAnimationFrame = 0
  /** */
  constructor(state: unknown, dom: HTMLDivElement) {
    this.state = state
    this.dom = dom
    const width = dom?.clientWidth || 1280 * wPxRatio()
    const height = dom?.clientWidth * (8 / 16) || 720 * hPxRatio()
    // this.canvas = canvas;
    // this.canvas.width = width;
    // this.canvas.height = height;
    this.stage = new Konva.Stage({
      container: dom,
      width,
      height,
      draggable: false,
      fill: 'white',
    })
    this.zoom = { ratio: 1, center: [width! / 2, height! / 2] }
    this.bgLayer.add(
      new Konva.Rect({
        x: 0,
        y: 0,
        name: EDrawingToolName.BgRect,
        width,
        height,
        fill: 'white',
        draggable: false,
      }),
    )
    this.stage.add(this.bgLayer)
    initBoard(this, this.stage, this.layers)
    this.brush()
  }
  /**清屏幕 */
  clearAll = () => {
    this.operat = ERecorderOperation.none
    if (this.layers.length > 0) {
      this.layers.forEach((layer: Konva.Shape) => {
        if (layer) {
          layer.remove()
        }
      })
    }
    this.bgLayer.clear()
  }

  /**回退 */
  backspacing() {
    this.operat = ERecorderOperation.none
    if (this.layers.length > 0) {
      const layer: Konva.Shape = this.layers.pop()!
      if (layer) {
        layer.remove()
      }
    }
  }
  brush = () => {
    //shape.draggable('true');
    this.operat = ERecorderOperation.brush
    brush(this.stage, this.color, this.bgLayer, this.layers)
  }
  setImage = (url: string, name: string) => {
    const layer = this.bgLayer
    const imageObj = new Image()
    const pos = { x: 0, y: 0 }
    imageObj.onload = () => {
      const img = new Konva.Image({
        x: pos.x,
        y: pos.y,
        name,
        resizeEnabled: true,
        draggable: false,
        image: imageObj,
        width: 320 * wPxRatio(),
        height: 180 * hPxRatio(),
      })
      // add the shape to the layer
      layer.add(img)
      layer.draw()
      this.layers.push(img)
      // layer.add(new Konva.Rect({x:-2,y:-2,width:1,height:1, fill: 'white',}))
    }
    imageObj.crossOrigin = 'Anonymous'
    imageObj.src = url
  }
  /**文字 */
  setText() {
    this.operat = ERecorderOperation.text
    /**生成文字 */
    createImageText(this.stage, this.color, this.layers, this.bgLayer)
  }
  /**图像 */
  setUploadImage() {
    this.operat = ERecorderOperation.image
  }
  drawGraph = (type: EGraph) => {
    switch (type) {
      case EGraph.line:
        this.operat = ERecorderOperation.line
        lineBrush(this.stage, this.color, this.bgLayer, this.layers)
        break
      case EGraph.triangle:
        this.operat = ERecorderOperation.triangle
        triangleBrush(this.stage, this.color, this.bgLayer, this.layers)
        break
      case EGraph.rectangle:
        this.operat = ERecorderOperation.rectangle
        rectangleBrush(this.stage, this.color, this.bgLayer, this.layers)
        break
      case EGraph.circle:
        this.operat = ERecorderOperation.circle
        circleBrush(this.stage, this.color, this.bgLayer, this.layers)
        break
      default:
        break
    }
  }
  /**
   * 清理画刷，选中等状态
   */
  flyback = () => {
    this.operat = ERecorderOperation.none
    //清理画刷
    clearBush(this.stage)
    //清除旋转状态
    const tr = this.stage.find(EDotDrawingToolName.Dotrotatetransform)
    tr.forEach((node) => node.remove())
    this.stage.find(EDotDrawingToolName.DotcloseShapebtn).forEach((node) => node.remove())
    if (this.activeShape && this.activeShape.draggable()) {
      this.activeShape.draggable(false)
    }
    // this.layers.forEach(node => node.draggable(false));
    // this.stage.draggable(true);
  }
  /** */
  // reflashToCanvas = () => {
  //   const ctx = this.canvas.getContext('2d');
  //   const width = this.stage.width();
  //   const height = this.stage.height();
  //   //ctx?.drawImage(this.stage.toCanvas({ x: 0, y: 0, width, height: height }), 0, 0, width, height);
  //   //ctx?.drawImage(this.bgLayer.getCanvas()._canvas , 0, 0, width, height);
  //   this.reflashRequestAnimationFrame = requestAnimationFrame(() => this.reflashToCanvas());
  // };
  // closeReflashCanvas = () => {
  //   cancelAnimationFrame(this.reflashRequestAnimationFrame);
  // };
}
